package org.rambadger.command.model;

import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.saga.annotation.AbstractAnnotatedSaga;
import org.axonframework.saga.annotation.EndSaga;
import org.axonframework.saga.annotation.SagaEventHandler;
import org.axonframework.saga.annotation.StartSaga;
import org.rambadger.command.command.AwardPoints;
import org.rambadger.command.event.ReviewFinalized;
import org.rambadger.command.event.SubmissionCreated;

import java.io.Serializable;


public class SubmissionSaga extends AbstractAnnotatedSaga implements Serializable {
    private static final long serialVersionUID = -664435199316025904L;
    private transient CommandGateway gateway;


    @StartSaga
    @SagaEventHandler(associationProperty = "submissionId", keyName = "fullSubmissionId")
    public void handle(SubmissionCreated event) {
        associateWith("submitterId", event.getUsername());
    }

    //Remove @EndSaga if reviews need to be retracted
    @EndSaga
    @SagaEventHandler(associationProperty = "submissionId", keyName = "fullSubmissionId")
    public void handle(ReviewFinalized event) {
        gateway.send(new AwardPoints.AwardSubmissionPoints(event.getSubmitterId(), event.getSubmissionPointsAwarded()));
        gateway.send(new AwardPoints.AwardReviewPoints(event.getReviewerId(), event.getReviewPointsAwarded()));

    }


    void setGateway(CommandGateway gateway) {
        this.gateway = gateway;
    }
}
